//
//  UserDataHelper.m
//  FoodCorner
//
//  Created by lanou3g on 16/3/11.
//  Copyright © 2016年 zhangchao. All rights reserved.
//

#import "UserDataHelper.h"
#import <RongIMKit/RongIMKit.h>

static UserDataHelper *helper = nil;
@implementation UserDataHelper

//+ (instancetype)shareInstance{
//    
//    if (helper==nil) {
//        helper = [[UserDataHelper allocWithZone:NULL]init];
//    }
//    return helper;
//    
//    
//}

+ (instancetype)shareInstance{
    
    static UserDataHelper *helper = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[UserDataHelper alloc]init];
        helper.myUser = [AVUser currentUser];
        helper.userType = [AVUser currentUser][@"userType"];
        if (helper.myUser != nil) {
            helper = [[UserDataHelper alloc]init];
        }
        
    });
    return helper;
}
//
////获取Token
//- (void)getToken
//{
//    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    [dic setValue:[AVUser currentUser].username forKey:@"name"];
//    [dic setValue:[AVUser currentUser].email forKey:@"userId"];
//    //取得当前用户的头像信息
//    
//    AVFile *file = [AVUser currentUser][@"Picture"];
//    [dic setValue:file.url forKey:@"portraitUri"];
//    //获取body
//    NSData *da = [ZC_AsynchronousBlock httpBodyFromParamDictionary:dic];
//    
//    [ZC_AsynchronousBlock asynchronousPOSTWithURLString:@"https://api.cn.ronghub.com/user/getToken.json" AppKey:@"uwd1c0sxdbad1" AppSecret:@"1ery3DRvC5k" body:da PassBlock:^(NSData *data) {
//        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//        //取得当前token
//        self.token = dict[@"token"];
//    }];
//}


- (void)getToken{
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:[AVUser currentUser].username forKey:@"name"];
    [dic setValue:[AVUser currentUser].username forKey:@"userId"];
    [dic setValue:@"http://img2.imgtn.bdimg.com/it/u=2714293153,1939755281&fm=21&gp=0.jpg" forKey:@"portraitUri"];
    //获取body
    NSData *data = [self httpBodyFromParamDictionary:dic];
    
    [self asynchronousPOSTWithURLString:@"https://api.cn.ronghub.com/user/getToken.json" AppKey:@"m7ua80gbu90qm" AppSecret:@"aDAmhMriIyFP" body:data PassBlock:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"获取到的Token是:%@",dict[@"token"]);
        self.token = dict[@"token"];
        
        //即时通讯登陆
        [[RCIM sharedRCIM] initWithAppKey:@"m7ua80gbu90qm"];
        NSString *token = [UserDataHelper shareInstance].token;
        [[RCIM sharedRCIM] connectWithToken:token success:^(NSString *userId) {
            NSLog(@"登录成功");
        } error:^(RCConnectErrorCode status) {
            NSLog(@"登录失败，失败代码为：%ld",status);
        } tokenIncorrect:^{
            NSLog(@"登录失败，token出错");
        }];
    }];
}


//提供给融云用户的信息
//- (void)getUserInfoWithUserId:(NSStaDAmhMriIyFPring *)userId completion:(void(^)(RCUserInfo* userInfo))completion
//{
//    //此处为了演示写了一个用户信息
//    if ([@"1" isEqual:userId]) {
//        RCUserInfo *user = [[RCUserInfo alloc]init];
//        user.userId = @"1";
//        user.name = @"测试1";
////        user.portraitUri = @"https://ss0.baidu.com/73t1bjeh1BF3odCf/it/u=1756054607,4047938258&fm=96&s=94D712D20AA1875519EB37BE0300C008";
//        
//        return completion(user);
//    }else if([@"2" isEqual:userId]) {
//        RCUserInfo *user = [[RCUserInfo alloc]init];
//        user.userId = @"2";
//        user.name = @"测试2";
//        user.portraitUri = @"https://ss0.baidu.com/73t1bjeh1BF3odCf/it/u=1756054607,4047938258&fm=96&s=94D712D20AA1875519EB37BE0300C008";
//        return completion(user);
//    }
//}


//数据请求
- (void)asynchronousPOSTWithURLString:(NSString *)urlString AppKey:(NSString *)appKey AppSecret:(NSString *)appSecret body:(NSData *)body PassBlock:(MyAsynchronousBlock)passBlock
{
    //获取一个随机标志
    NSString * nonce = [NSString stringWithFormat:@"%d",arc4random()];
    //获取时间戳
    NSString * timestamp = [[NSString alloc] initWithFormat:@"%ld",(NSInteger)[NSDate timeIntervalSinceReferenceDate]];
    //创建URL
    NSURL *url = [NSURL URLWithString:urlString];
    //创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求超时时间
    request.timeoutInterval = 10;
    
    //配置http header
    [request setValue:appKey forHTTPHeaderField:@"App-Key"];
    [request setValue:nonce forHTTPHeaderField:@"Nonce"];
    [request setValue:timestamp forHTTPHeaderField:@"Timestamp"];
    [request setValue:appSecret forHTTPHeaderField:@"appSecret"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    //设置HTTPBody
    [request setHTTPBody:body];
    //设置请求方式
    [request setHTTPMethod:@"POST"];
    //创建会话
    NSURLSession *session = [NSURLSession sharedSession];
    //创建数据处理的任务
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSData *da = data;
        dispatch_async(dispatch_get_main_queue(), ^{
            //利用passBlock传值
            passBlock(da);
        });
    }];
    [dataTask resume];
}

//数据转换
- (NSData *)httpBodyFromParamDictionary:(NSDictionary *)param
{
    NSMutableString * data = [NSMutableString string];
    for (NSString * key in param.allKeys) {
        [data appendFormat:@"%@=%@&",key,param[key]];
    }
    return [[data substringToIndex:data.length-1] dataUsingEncoding:NSUTF8StringEncoding];
}


@end
